package com.example.fengyungo.controller.user.user;

import com.example.fengyungo.constant.MsgConstant;
import com.example.fengyungo.constant.OrderConstant;
import com.example.fengyungo.domain.dto.OrderCreditDTO;
import com.example.fengyungo.domain.dto.OrderDetailsDTO;
import com.example.fengyungo.domain.entity.Order;
import com.example.fengyungo.domain.pojo.Driver;
import com.example.fengyungo.domain.pojo.Thing;
import com.example.fengyungo.domain.pojo.User;
import com.example.fengyungo.domain.vo.OrderDetailsVO;
import com.example.fengyungo.result.Result;
import com.example.fengyungo.service.DriverService;
import com.example.fengyungo.service.OrderService;
import com.example.fengyungo.service.ThingService;
import com.example.fengyungo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/user/user")
public class UserOrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private ThingService thingService;

    @Autowired
    private DriverService driverService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 清理缓存数据
     *
     * @param pattern String
     */
    private void cleanCache(String pattern) {
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }

    /**
     * 添加订单
     *
     * @param orderDetailsDTO 订单
     * @return 订单是否添加成功
     */
    @PostMapping("/add")
    public Result<Boolean> addOrder(@RequestBody OrderDetailsDTO orderDetailsDTO) {
        Order order = Order.builder()
                .userId(orderDetailsDTO.getUserId())
                .number(orderDetailsDTO.getNumber())
                .begin(orderDetailsDTO.getBegin())
                .end(orderDetailsDTO.getEnd())
                .earliestTime(orderDetailsDTO.getEarliestTime())
                .latestTime(orderDetailsDTO.getLatestTime())
                .note(orderDetailsDTO.getNote())
                .price(orderDetailsDTO.getPrice())
                .payStatus(orderDetailsDTO.getPayStatus())
                .build();
        Boolean res = orderService.addOrder(order);
        Thing thing = Thing.builder()
                .number(orderDetailsDTO.getNumber())
                .length(orderDetailsDTO.getLength())
                .width(orderDetailsDTO.getWidth())
                .height(orderDetailsDTO.getHeight())
                .weight(orderDetailsDTO.getWeight())
                .image(orderDetailsDTO.getImage())
                .build();
        Integer integer = thingService.addThing(thing);
        if (integer < 1) {
            res = false;
        }
        if (!res) {
            return Result.error(MsgConstant.ORDER_ADD_FAIL);
        }
        // 清除缓存
        cleanCache("fengyungoorder*");
        return Result.success(res);
    }

    /**
     * 根据用户id查询用户发布的订单
     *
     * @param userId 用户id
     * @return List<Order>
     */
    @GetMapping("/orders/{userId}")
    @Cacheable(value = "order", key = "'getOrdersByUserId'+#userId")
    public Result<List<OrderDetailsVO>> getOrdersByUserId(@PathVariable String userId) {
        return orderService.getOrdersByUserId(userId);
    }

    /**
     * 修改货物状态为已收货
     *
     * @param number String
     * @return Result
     */
    @PutMapping("/gotGoods/{number}")
    public Result<Boolean> gotGoods(@PathVariable String number) {
        Order order = new Order();
        order.setNumber(number);
        order.setOrderStatus(OrderConstant.HAS_GOT_GOODS);
        Integer res = orderService.updateOrderByNumber(order);
        // TODO: 2024/2/15 若未支付，提醒支付
        if (res > 0) {
            // 清除缓存
            cleanCache("fengyungoorder*");
            return Result.success();
        } else {
            return Result.error(MsgConstant.ORDER_STATUS_UPDATE_FAIL);
        }
    }

    /**
     * 设订单未完成，设置订单为未支付、状态为取消
     *
     * @param number String
     * @return Result
     */
    @PutMapping("/notFinished/{number}")
    public Result<Boolean> setNotFinished(@PathVariable String number) {
        Order order = new Order();
        order.setNumber(number);
        order.setPayStatus(OrderConstant.NO_PAID);
        order.setOrderStatus(OrderConstant.CANCELED_NOT_FINISHED);
        Integer res = orderService.updateOrderByNumber(order);
        if (res > 0) {
            // 清除缓存
            cleanCache("fengyungoorder*");
            return Result.success();
        } else {
            return Result.error(MsgConstant.ORDER_STATUS_UPDATE_FAIL);
        }
    }

    /**
     * 订单完成，设置订单为已支付
     *
     * @param number String
     * @return Result
     */
    @PutMapping("/hasPaid/{number}")
    public Result<Boolean> hasPaid(@PathVariable String number) {
        Order order = new Order();
        order.setNumber(number);
        order.setPayStatus(OrderConstant.HAS_PAID);
        Integer res = orderService.updateOrderByNumber(order);
        if (res > 0) {
            // 清除缓存
            cleanCache("fengyungoorder*");
            return Result.success();
        } else {
            return Result.error(MsgConstant.ORDER_STATUS_UPDATE_FAIL);
        }
    }

    /**
     * 取消订单
     *
     * @param number String
     * @return Result
     */
    @PutMapping("/cancelOrder/{number}")
    public Result<Boolean> cancelOrder(@PathVariable String number) {
        Order order = new Order();
        order.setNumber(number);
        order.setOrderStatus(OrderConstant.CANCELED_HAS_FINISHED);
        Integer res = orderService.updateOrderByNumber(order);
        if (res > 0) {
            // 清除缓存
            cleanCache("fengyungoorder*");
            return Result.success();
        } else {
            return Result.error(MsgConstant.ORDER_STATUS_UPDATE_FAIL);
        }
    }

    /**
     * 司机接受订单
     *
     * @param receiverId 接受者id，司机id
     * @param number     订单编号
     * @return Result
     */
    @PutMapping("/{receiverId}/{number}")
    public Result<Boolean> receiveOrder(@PathVariable String receiverId, @PathVariable String number) {
        // 接受订单
        Boolean res = orderService.updateReceiverIdAndOrderStatusByNumber(receiverId, number);
        // 清除缓存
        cleanCache("fengyungoorder*");
        if (res) {
            return Result.success();
        } else {
            return Result.error("");
        }
    }

    /**
     * 修改订单评分
     *
     * @param orderCreditDTO 订单详情
     * @return Result
     */
    @PutMapping("/credit")
    public Result changeOrderCredit(@RequestBody OrderCreditDTO orderCreditDTO) {
        // 订单编号
        String number = orderCreditDTO.getNumber();
        // 订单评分
        Float credit = orderCreditDTO.getCredit();
        // 接单者id（司机id）
        String receiverId = orderCreditDTO.getReceiverId();
        Integer res = orderService.updateCredit(number, credit);
        if (res > 0) {
            // 评分发生改变时修改司机评分
            driverService.updateCredit(receiverId);
        }
        // 清除缓存
        cleanCache("fengyungoorder*");
        return Result.success();
    }
}
